package vip.zhenzicheng.concurrent_program.thread.sgg.completablefuture;

import java.util.concurrent.*;

/**
 * @author zhenzicheng
 * @date 2022-06-10 15:36
 */
public class CompletableFutureUseDemo {

  static ExecutorService threadPool = Executors.newFixedThreadPool(3);

  public static void main(String[] args) {
    CompletableFuture.supplyAsync(() -> {
      System.out.println(Thread.currentThread().getName() + "----come in");
      int result = ThreadLocalRandom.current().nextInt(10);
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      if (result % 2 == 0) {
        int i = 10 / 0;
      }
      System.out.println("----1s后出结果:" + result);
      return result;
    }, threadPool).whenComplete((result, exception) -> {
      if (exception == null) {
        System.out.println("----计算完成，更新变量:" + result);
      }
    }).exceptionally(e -> {
      e.printStackTrace();
      System.out.println("异常情况：" + e.getCause() + "\t" + e.getMessage());
      return null;
    });

    System.out.println(Thread.currentThread().getName() + "线程先去忙其他任务");
    // 主线程不要立刻结束，否则 CompletableFuture 默认使用的线程池会立即关闭，类似于守护线程。
    // try {
    //   TimeUnit.SECONDS.sleep(3);
    // } catch (InterruptedException e) {
    //   e.printStackTrace();
    // }
    threadPool.shutdown(); // 会将剩余任务执行完后优雅关闭，不接受新任务
  }
}
